#include "game_mysql.h"
#include "game_log.h"

using namespace sql;
using namespace std;

bool GameMysql::initMysql(std::string url, int port, std::string username, std::string password)
{
	url_ = url;
	username_ = username;
	port_ = port;
	password_ = password;
	connection_ = Connect();
	return (connection_ != NULL);
}

sql::PreparedStatement * GameMysql::GetPrepare(const std::string & sql)
{
	auto itr = _prepare_list.find(sql);
	if (itr != _prepare_list.end())
	{
		itr->second->_prep->clearParameters();
		return itr->second->_prep;
	}
	else
	{
		auto conn = GetConnect();
		auto prep = conn->prepareStatement(sql);
		auto stmt = new MysqlStmtPrepare(sql, prep);
		_prepare_list.insert(make_pair(sql, stmt));
		return prep;
	}
}

bool GameMysql::Reconnect()
{
	ClearPrep();
	connection_ = Connect();
	return (connection_ != NULL);
}

sql::Connection * GameMysql::Connect()
{
	try
	{
		driver_ = sql::mysql::get_mysql_driver_instance();
	}
	catch (sql::SQLException&e)
	{
		GAME_LOG.error("ConnPool, get_driver_instance faied. error info[%s]\n", e.what());
		return NULL;
	}
	catch (std::runtime_error&e)
	{
		GAME_LOG.error("ConnPool, RUNTIME ERROR!,error info[%s].\n", e.what());
		return NULL;
	}
	try
	{
		sql::Connection * conn = driver_->connect(url_, username_, password_);//建立连接
		return conn;
	}
	catch (sql::SQLException&e)
	{
		GAME_LOG.error("[ERR]CreateConnection, error info[%s].\n", e.what());
	}
	catch (std::runtime_error&e)
	{
		GAME_LOG.error("[ERR]CreateConnection, runtime error!, error info[%s].\n", e.what());
	}
	return NULL;
}

void GameMysql::ClearPrep()
{
	for (auto info : _prepare_list)
	{
		delete info.second;
	}
	_prepare_list.clear();
}
